﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Windows;
using System.Windows.Controls;
using Domain;
using Microsoft.AspNet.SignalR.Client;
using Tricom.Tricommerce.Domain;
using MessageGroupReceiver = Domain.MessageGroupReceiver;
using MessageUserReceiver = Domain.MessageUserReceiver;
using PageType = Domain.PageType;
using Task = Domain.Task;

namespace SilverlightRest
{
    public partial class MainPage : UserControl
    {
        public MainPage()
        {
            InitializeComponent();
            //RegisterSignalR();
        }

        IHubProxy hub;
        HubConnection connection = new HubConnection("http://localhost:51553/");

        private async void RegisterSignalR()
        {
            hub = connection.CreateHubProxy("MyHub");
            await connection.Start().ConfigureAwait(false);
            hub.Subscribe("hello");
            hub.On<string>("hello", OnData);    
        }

        private void OnData(string obj)
        {
            if (Dispatcher.CheckAccess())
                TextBoxOut.Text = obj;
            else
                this.Dispatcher.BeginInvoke(new Action<string>(OnData), obj);

            
        }

        private async void Button_Click(object sender, RoutedEventArgs e)
        {

            string os = Environment.OSVersion.Platform.ToString();
            string version = Environment.OSVersion.Version.ToString();

            MessageBox.Show(string.Format("OS: {0} Version: {1}", os, version));

            //RegisterSignalR();
            var person = new Person { Name = "morten" };
            person.Receivers.Add(new MessageGroupReceiver { GroupName = "xxxxx" });
            person.Receivers.Add(new MessageUserReceiver { UserName = "yyyyy" });
            var workPlace = new WorkPlace { WorkPlaceName = "Miracle A/S", Person = person };
            person.Tasks = new Dictionary<int, Domain.Task>();
            person.Tasks.Add(new KeyValuePair<int, Task>(123, new Domain.Task { TaskName = "my task" }));
            person.WorkPlace = workPlace;
            try
            {
                var result = await RestClient.PostWithRetry<Person>("person/updateperson", person);
                MessageBox.Show("Got a person called: " + result.Name);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Failed: " + ex.Message);
            }
        }

        private void TextBox_OnTextChanged(object sender, TextChangedEventArgs e)
        {
            hub.Invoke("hello", ((TextBox)sender).Text);
        }
    }
}
